"""
添加脚本对话框
"""
from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                           QLineEdit, QRadioButton, QComboBox,
                           QPushButton, QMessageBox, QWidget, QButtonGroup)
from PyQt6.QtCore import Qt
from typing import Dict, Any, List
import time
from com.db.order_account_manager import OrderAccountManager
from com.db.script_manager import ScriptManager
from com.db.script_task_manager import ScriptTaskManager
from com.db.script_scan_account_manager import ScriptScanAccountManager
from gui.widgets.scan_account_dialog import ScanAccountDialog
from gui.widgets.task_dialog import TaskDialog

class ScriptDialog(QDialog):
    """添加脚本对话框"""
    
    def __init__(self, parent=None, script_id: int = None):
        super().__init__(parent)
        self.script_id = script_id
        self.setWindowTitle("编辑脚本" if script_id else "新增脚本")
        self.setFixedSize(500, 600)
        self.order_account_manager = OrderAccountManager()
        self.script_manager = ScriptManager()
        self.script_task_manager = ScriptTaskManager()
        self.script_scan_account_manager = ScriptScanAccountManager()
        self.selected_scan_accounts = []  # 存储选中的扫货账号
        self.selected_tasks = []  # 存储选中的任务
        self.setup_ui()
        self.load_order_accounts()
        
        if script_id:
            self.load_script_data()
            
    def setup_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        layout.setSpacing(20)
        layout.setContentsMargins(20, 20, 20, 20)
        
        # 脚本名称
        name_layout = QHBoxLayout()
        name_label = QLabel("脚本名称")
        name_label.setFixedWidth(80)
        self.name_input = QLineEdit()
        self.name_input.setPlaceholderText("随意填写你觉得好记的名称")
        name_layout.addWidget(name_label)
        name_layout.addWidget(self.name_input)
        layout.addLayout(name_layout)
        
        # 是否自动发起报价
        price_layout = QHBoxLayout()
        price_label = QLabel("是否自动发起报价")
        price_label.setFixedWidth(80)
        self.price_group = QButtonGroup()
        self.price_yes = QRadioButton("是")
        self.price_no = QRadioButton("否")
        self.price_group.addButton(self.price_yes)
        self.price_group.addButton(self.price_no)
        self.price_yes.setChecked(True)
        price_layout.addWidget(price_label)
        price_layout.addWidget(self.price_yes)
        price_layout.addWidget(self.price_no)
        price_layout.addStretch()
        layout.addLayout(price_layout)
        
        # 选择下单账号
        account_layout = QHBoxLayout()
        account_label = QLabel("选择下单账号")
        account_label.setFixedWidth(80)
        self.account_combo = QComboBox()
        self.account_combo.setPlaceholderText("选择下单账号")
        account_layout.addWidget(account_label)
        account_layout.addWidget(self.account_combo)
        layout.addLayout(account_layout)
        
        # 选择扫货账号
        scan_account_layout = QHBoxLayout()
        scan_account_label = QLabel("选择扫货账号")
        scan_account_label.setFixedWidth(80)
        self.scan_account_btn = QPushButton("已选0个 点击选择")
        self.scan_account_btn.clicked.connect(self.select_scan_accounts)
        scan_account_layout.addWidget(scan_account_label)
        scan_account_layout.addWidget(self.scan_account_btn)
        layout.addLayout(scan_account_layout)
        
        # 选择扫货任务
        scan_task_layout = QHBoxLayout()
        scan_task_label = QLabel("选择扫货任务")
        scan_task_label.setFixedWidth(80)
        self.scan_task_btn = QPushButton("已选0个 点击选择")
        self.scan_task_btn.clicked.connect(self.on_select_tasks)
        scan_task_layout.addWidget(scan_task_label)
        scan_task_layout.addWidget(self.scan_task_btn)
        layout.addLayout(scan_task_layout)
        
        # 是否启动
        active_layout = QHBoxLayout()
        active_label = QLabel("是否启动")
        active_label.setFixedWidth(80)
        self.active_group = QButtonGroup()
        self.active_yes = QRadioButton("是")
        self.active_no = QRadioButton("否")
        self.active_group.addButton(self.active_yes)
        self.active_group.addButton(self.active_no)
        self.active_yes.setChecked(True)
        active_layout.addWidget(active_label)
        active_layout.addWidget(self.active_yes)
        active_layout.addWidget(self.active_no)
        active_layout.addStretch()
        layout.addLayout(active_layout)
        
        # 按钮区域
        btn_layout = QHBoxLayout()
        self.confirm_btn = QPushButton("确定")
        self.cancel_btn = QPushButton("取消")
        self.confirm_btn.clicked.connect(self.accept)
        self.cancel_btn.clicked.connect(self.reject)
        btn_layout.addStretch()
        btn_layout.addWidget(self.confirm_btn)
        btn_layout.addWidget(self.cancel_btn)
        layout.addLayout(btn_layout)
        
        # 设置样式
        self.setStyleSheet("""
            QDialog {
                background-color: white;
            }
            QLabel {
                font-size: 12px;
                color: #606266;
            }
            QLineEdit {
                padding: 5px;
                border: 1px solid #dcdfe6;
                border-radius: 2px;
                font-size: 12px;
                color: #606266;
            }
            QLineEdit:focus {
                border-color: #409eff;
            }
            QRadioButton {
                font-size: 12px;
                color: #606266;
            }
            QComboBox {
                padding: 5px;
                border: 1px solid #dcdfe6;
                border-radius: 2px;
                font-size: 12px;
                color: #606266;
            }
            QComboBox:focus {
                border-color: #409eff;
            }
            QPushButton {
                padding: 5px 15px;
                background-color: #409eff;
                color: white;
                border: none;
                border-radius: 2px;
                font-size: 12px;
                min-width: 60px;
            }
            QPushButton:hover {
                background-color: #66b1ff;
            }
            QPushButton#cancel_btn {
                background-color: white;
                color: #606266;
                border: 1px solid #dcdfe6;
            }
            QPushButton#cancel_btn:hover {
                color: #409eff;
                border-color: #c6e2ff;
                background-color: #ecf5ff;
            }
        """)
        
        # 设置对象名以便应用特定样式
        self.cancel_btn.setObjectName("cancel_btn")
        
    def load_order_accounts(self):
        """加载下单账号数据"""
        accounts = self.order_account_manager.get_active_accounts()
        for account in accounts:
            self.account_combo.addItem(account['name'], account['id'])
            
    def select_scan_accounts(self, selected_accounts=None):
        """选择扫货账号"""
        try:
            print("打开选择扫货账号对话框")
            print(f"当前已选账号: {self.selected_scan_accounts}")
            dialog = ScanAccountDialog(self, selected_accounts=selected_accounts if selected_accounts else self.selected_scan_accounts)
            if dialog.exec():
                self.selected_scan_accounts = dialog.get_selected_accounts()
                self.scan_account_btn.setText(f"已选{len(self.selected_scan_accounts)}个 点击选择")
        except Exception as e:
            import traceback
            error_msg = f"选择扫货账号失败: {str(e)}\n{traceback.format_exc()}"
            print(f"错误: {error_msg}")
            QMessageBox.critical(self, "错误", error_msg)
            
    def on_select_tasks(self):
        """打开任务选择对话框"""
        dialog = TaskDialog(self, [task['id'] for task in self.selected_tasks])
        if dialog.exec():
            self.selected_tasks = dialog.get_selected_tasks()
            self.scan_task_btn.setText(f"已选{len(self.selected_tasks)}个 点击选择")
            
    def load_script_data(self):
        """加载脚本数据"""
        try:
            # 1. 加载脚本基本信息
            script = self.script_manager.get_script_by_id(self.script_id)
            if not script:
                QMessageBox.warning(self, "错误", "脚本不存在")
                self.reject()
                return
                
            print(f"加载脚本数据: {script}")
            
            # 2. 设置基本信息
            self.name_input.setText(script.get('name', ''))
            self.price_yes.setChecked(script.get('is_auto_offer') == 1)
            self.price_no.setChecked(script.get('is_auto_offer') == 0)
            
            # 设置下单账号
            order_account_id = script.get('order_account_id')
            if order_account_id:
                index = self.account_combo.findData(order_account_id)
                if index >= 0:
                    self.account_combo.setCurrentIndex(index)
                    
            # 设置节点
            self.active_yes.setChecked(script.get('node_index') == 1)
            self.active_no.setChecked(script.get('node_index') == 0)
            
            # 3. 加载关联的扫货账号
            accounts = self.script_scan_account_manager.get_scan_accounts_by_script_id(self.script_id)
            print(f"加载关联的扫货账号: {accounts}")
            self.selected_scan_accounts = accounts
            if accounts:
                self.scan_account_btn.setText(f"已选{len(accounts)}个 点击选择")
                
            # 4. 加载关联的任务
            tasks = self.script_task_manager.get_by_script_id(self.script_id)
            print(f"加载关联的任务: {tasks}")
            self.selected_tasks = tasks
            if tasks:
                self.scan_task_btn.setText(f"已选{len(tasks)}个 点击选择")
                
        except Exception as e:
            import traceback
            error_msg = f"加载脚本数据失败: {str(e)}\n{traceback.format_exc()}"
            print(f"错误: {error_msg}")
            QMessageBox.critical(self, "错误", error_msg)
            self.reject()

    def get_data(self) -> Dict[str, Any]:
        """获取表单数据"""
        return {
            'name': self.name_input.text(),
            'is_auto_offer': 1 if self.price_yes.isChecked() else 0,
            'order_account_id': self.account_combo.currentData(),
            'node_index': 1 if self.active_yes.isChecked() else 0,
            'status': 1,
            'run_status': 0,
            'latest_times': 0
        }
        
    def accept(self):
        """确认按钮点击事件"""
        # 验证表单数据
        if not self.name_input.text():
            QMessageBox.warning(self, "提示", "请输入脚本名称")
            return
            
        if not self.account_combo.currentData():
            QMessageBox.warning(self, "提示", "请选择下单账号")
            return
            
        if not self.selected_scan_accounts:
            QMessageBox.warning(self, "提示", "请选择扫货账号")
            return
            
        if not self.selected_tasks:
            QMessageBox.warning(self, "提示", "请选择扫货任务")
            return
            
        try:
            # 1. 保存脚本基本信息
            script_data = self.get_data()
            print(f"脚本数据: {script_data}")
            
            script_data['account_count'] = len(self.selected_scan_accounts)
            script_data['task_count'] = len(self.selected_tasks)
            print(f"添加计数后的脚本数据: {script_data}")
            
            if self.script_id:
                # 更新模式
                print(f"更新脚本，ID: {self.script_id}")
                script_data['id'] = self.script_id
                self.script_manager.update_script(self.script_id, script_data)
                
                # 删除旧的关联
                self.script_task_manager.delete_by_script_id(self.script_id)
                self.script_scan_account_manager.delete_by_script_id(self.script_id)
                script_id = self.script_id
            else:
                # 新增模式
                script_id = self.script_manager.add_script(script_data)
                print(f"保存脚本成功，ID: {script_id}")
            
            # 2. 保存脚本任务关联
            for task in self.selected_tasks:
                task_data = {
                    'script_id': script_id,
                    'task_id': task['id'],
                    'status': 0,
                    'create_at': time.strftime('%Y-%m-%d %H:%M:%S'),
                    'update_at': int(time.time())
                }
                print(f"保存任务关联: {task_data}")
                self.script_task_manager.add(task_data)
                
            # 3. 保存脚本扫货账号关联
            for account in self.selected_scan_accounts:
                print(f"保存账号关联: script_id={script_id}, account_id={account['id']}")
                self.script_scan_account_manager.add(script_id, account['id'])
                
            # 4. 刷新父页面的表格
            if isinstance(self.parent(), QWidget):
                if hasattr(self.parent(), 'load_scripts'):
                    self.parent().load_scripts()
                
            super().accept()
        except Exception as e:
            import traceback
            error_msg = f"保存失败: {str(e)}\n{traceback.format_exc()}"
            print(f"错误: {error_msg}")
            QMessageBox.critical(self, "错误", error_msg)
